package com.jinyuan.options.login;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.android.threadpool.IActivity;
import com.android.threadpool.Task;
import com.jinyuan.R;
import com.jinyuan.options.LeftMenuActivity;
import com.jinyuan.options.OptionsFragment;
import com.jinyuan.options.userinfo.service.UserInfoService;
import com.jinyuan.request.RequestURL;
import com.jinyuan.service.MobileApplication;
import com.jinyuan.service.ParentHandlerService;
import com.jinyuan.service.TaskID;
import com.jinyuan.view.NewFontsEditText;

/**
 * 用户登陆
 * 
 * @author azuryleaves
 * @since 2014-1-3 下午12:14:13
 * @version 1.0
 * 
 */
public class LoginFragment extends OptionsFragment implements IActivity {

	private View view;
	private NewFontsEditText login_username, login_password;
	private CheckBox save_password;
	public static SharedPreferences preferences;
	private Button parentdialog_confirm_Button;
	private Animation shake;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		preferences = getActivity().getSharedPreferences(MobileApplication.TAG,
				Context.MODE_PRIVATE);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		MobileApplication.allIActivity.add(this);
		view = inflater.inflate(R.layout.login_tab1, container, false);
		parentdialog_confirm_Button = (Button) ((ViewGroup) container
				.getParent()).findViewById(R.id.parentdialog_confirm_Button);
		parentdialog_confirm_Button.setOnClickListener(clickListener);
		init();
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		login_username.setText(preferences.getString("phonenum", ""));
		login_password.setText(preferences.getString("password", ""));
		save_password.setChecked(preferences.getBoolean("isChecked", false));
	}

	private boolean checkEmpty() {
		if ("".equals(login_username.getText().toString().trim())) {
			Toast.makeText(getActivity(), R.string.account, Toast.LENGTH_SHORT)
					.show();
			login_username.startAnimation(shake);
		} else {
			if ("".equals(login_password.getText().toString().trim())) {
				Toast.makeText(getActivity(), R.string.password,
						Toast.LENGTH_SHORT).show();
				login_password.startAnimation(shake);
			} else {
				return true;
			}
		}
		return false;
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.parentdialog_confirm_Button:
				if (checkEmpty()) {
					saveOrDeleteInfo(save_password.isChecked());
					Map<String, Object> map = new HashMap<String, Object>();
					map.put(ParentHandlerService.URL, RequestURL.getLogin());
					map.put("j_username", login_username.getText().toString()
							.trim());
					map.put("j_password", login_password.getText().toString()
							.trim());
					Task task = new Task(TaskID.TASK_LOGIN, map, this
							.getClass().getName(), "-用户登陆-");
					loadingDialog.show();
					MobileApplication.poolManager.addTask(task);
				}
				break;
			default:
				break;
			}
		}
	};

	private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			int checkbox = buttonView.getId();
			switch (checkbox) {
			case R.id.save_password:
				if (isChecked) {
					if (checkEmpty()) {
						saveOrDeleteInfo(isChecked);
					} else {
						save_password.setChecked(false);
					}
				} else {
					saveOrDeleteInfo(false);
				}
				break;

			default:
				break;
			}
		}
	};

	private void saveOrDeleteInfo(boolean isSave) {
		if (isSave) {
			preferences
					.edit()
					.putString("phonenum",
							login_username.getText().toString().trim())
					.putString("password",
							login_password.getText().toString().trim())
					.putBoolean("isChecked", true).commit();
		} else {
			preferences.edit().clear().commit();
			preferences.edit().putBoolean("isReinstall", false).commit();
		}
	}

	@Override
	public void init() {
		login_username = (NewFontsEditText) view
				.findViewById(R.id.login_username);
		login_password = (NewFontsEditText) view
				.findViewById(R.id.login_password);
		save_password = (CheckBox) view.findViewById(R.id.save_password);
		save_password.setOnCheckedChangeListener(checkedChangeListener);
		shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
	}

	@Override
	public void refresh(int taskID, Object... params) {
		loadingDialog.cancel();
		if (params != null) {
			if (params[0] != null) {
				try {
					JSONObject jsonObject = new JSONObject((String) params[0]);
					String loginState = jsonObject.getString("loginState");
					if ("error".equals(loginState)) {
						Toast.makeText(getActivity(),
								jsonObject.getString("errorMsg"),
								Toast.LENGTH_SHORT).show();
					} else if ("success".equals(loginState)) {
						Toast.makeText(getActivity(), R.string.login_success,
								Toast.LENGTH_SHORT).show();
						getActivity().finish();
						UserInfoService.jsonObject = jsonObject.getJSONObject("users");
						LeftMenuActivity.leftmenu_username_TextView
								.setText(jsonObject.getJSONObject("users")
										.getString("username"));
						LeftMenuActivity.logout_Button.setVisibility(View.VISIBLE);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				loadingDialog.showTimeOut();
			}
		} else {
			loadingDialog.showTimeOut();
		}
	}

	@Override
	public void closeLoadingView() {
		loadingDialog.cancel();
	}

}